package ni;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * This class handles sending a file via TCP
 */
public class TCPSender{

	/**
	 * socket port
	 * link to the ni
	 */
	private final int port = 16055;
	private Socket sock;
	private ChatNI chatNI;
	
	/**
	 * @param chatNI is a link to the chatNI
	 */
	public TCPSender(ChatNI chatNI) {
		this.chatNI = chatNI;
	}
	
	/**
	 * the file chosen is sent via TCP
	 * @param ip is the ip address of the recipient
	 * @param nameFile is the name of the file to send
	 */
	public void sendFile(InetAddress ip, String nameFile){
		try {
			this.sock = new Socket(ip, this.port);
			byte[] mybytearray = new byte[1024];
			InputStream is = this.sock.getInputStream();
		    FileOutputStream fos = new FileOutputStream(nameFile);
		    BufferedOutputStream bos = new BufferedOutputStream(fos);
		    int bytesRead = is.read(mybytearray, 0, mybytearray.length);
		    bos.write(mybytearray, 0, bytesRead);
		    bos.close();
		    sock.close();
		} catch (IOException e) {e.printStackTrace();}    
	}
}
